// pages/pageAddition/add.js
const app = getApp();
const call = require('../../../utils/request.js');
const cabinTable = require('../../../utils/cabin.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    windowHeight: 0,
    array: [],
    index: 0,
    kindList: [],
    activeKind: 0,
    foodKindList: [],
    waitList: [],
    loading: true,
    info: '',
    dateOfProduct: 0,
    shelfLife: 0,
    imageLoading: true,
    activeFood: '',
    sliderLeft: (0, '1000rpx', 0),
    pY: 0,
    imgErr: [],
    activeCabin: ''
  },
  onSubmitFood() {
    if (this.data.waitList.length === 0) {
      wx.showToast({
        title: '你什么都没选哟!',
        icon: 'none',
        duration: 2000
      })
    } else {
      this._batchFridgeFoods(); //添加食材进冰箱
    }
  },
  // piker回调
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e)
    this.setData({
      activeCabin: this.data.array[e.detail.value]
    })
  },
  // 图片错误回调
  imageErr(e) {
    console.log('错误的图片', e);
    const arrErr = this.data.imgErr.slice();
    arrErr.push(e.currentTarget.dataset.errId);
    this.setData({
      imgErr: arrErr
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    //设置选择的舱室
    that.setData({
      activeCabin: app.globalData.foodmanager.activeCabin
    })
    // 获取屏幕参数
    wx.getSystemInfo({
      success(res) {
        that.setData({
          windowHeight: res.windowHeight
        });
        console.log(res.windowHeight)
      }
    });
     //获取食材种类列表
    this._getNewPublicFoodCatalogList();
    //先判断缓存中是否有食材列表，如果有就不重复获取，否则请求并获取
    wx.getStorage({ 
      key: 'foodBody',
      success(res) {//本地有食材库存
        that.onOpenKind()
      },
      fail(res) {//本地无食材库存
        //获取全部食材种类列表
        that._getNewPublicFoodSimpleList(-1); 
      }
    });
    wx.getStorage({
      key: 'cabins',
      success(res) {
        that.setData({
          array: res.data.map(i => {
            return i.cabinName
          })
        })
      },
      fail(){
        wx.showToast({
          title: '网络好像开小差了，获取不到舱室',
          icon:'none'
        })
      }
    })
  },
  // 上传添加的食材
  _batchFridgeFoods() {
    var that = this;
    wx.showLoading({
      title: '正在操作，请稍后...',
    })
    const cabinID = cabinTable.cabins.find(i => i.cabinName === this.data.activeCabin).cabinId;//根据对应舱室名以及本地对照列表获取舱室ID
    const unloadList = this.data.waitList.map((i, index) => {
      return {
        dateOfProduct: i.dateOfProduct,
        createTime: i.dateOfProduct,
        deviceId: app.globalData.mac,
        location: cabinID,
        id: i.id,
        name: i.name,
        deviceid: app.globalData.mac,
        imgUrl: i.picUrl,
        shelfLife: i.shelfLife
      }
    })
    const url = `/service/v1/food/batchFridgeFoods?access_token=${app.globalData.access_token}`;
    const params = {
      deviceId: app.globalData.mac,
      addFridgeFoods: unloadList
    };
    call.postData(url, params, res => {
      wx.hideLoading(); //隐藏加载
      wx.showToast({
        title: '添加食材成功!',
        icon: 'success',
        duration: 2000
      });
      wx.navigateBack({
        delta: 1 //返回页面的数字
      })
    }, err => {
      wx.showToast({
        title: '添加食材失败!',
        icon: 'fail',
        duration: 2000
      })
      wx.navigateBack({
        delta: 1 //返回页面的数字
      })
    });
  },
  // 获取种类列表
  _getNewPublicFoodCatalogList() {
    const url = `/service/v1/food/getNewPublicFoodCatalogList?access_token=${app.globalData.access_token}`;
    const params = {
      "updateDate": 1506787200000
      // "updateDate": Date.parse(new Date())
    };
    call.postData(url, params, res => {
      console.log('查询食材种类成功', res);
      this.setData({
        kindList: res.data
      })
    }, err => {
      console.log('查询食材种类失败', err);
      wx.navigateBack({
        delta: 1 //返回页面的数字
      })
    });
  },
  //获取全部食材种类列表
  _getNewPublicFoodSimpleList(id) {
    const url = `/service/v1/food/getNewPublicFoodSimpleList?access_token=${app.globalData.access_token}`;
    const params = {
      "classifyFaceId": id
    };
    call.postData(url, params, res => {
      console.log('获取所有种类食材成功', res)
      wx.setStorage({
        key: 'foodBody',
        data: res.data
      })
      this.onOpenKind()
    }, err => {
      console.log('获取食材种类库失败', err);
      wx.navigateBack({
        delta: 1 //返回页面的数字
      })
    });
  },
  onOpenKind(e) { //种类点击事件
    if (e && (e.currentTarget.dataset.kindId === '99')) {
      // this.tapCustom()
      wx.showToast({
        title: '开发中,敬请期待...',
        icon: 'none'
      })
    } else {
      var that = this;
      this.setData({ //设置活跃种类
        activeKind: e ? e.currentTarget.dataset.index : 0,
        loading: false
      });
      wx.getStorage({ //从Storage中获取食材列表并过滤展示
        key: 'foodBody',
        success(res) {
          const filterArr = res.data.filter(i => i.classifyFaceId === (e ? e.currentTarget.dataset.kindId : 1));
          that.setData({
            foodKindList: filterArr
          })
        },
        fail() {
          wx.showToast({
            title: '获取本地食材列表失败！',
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
  },
  // 获取自定义食材
  // tapCustom() {
  //   const url = `/service/app/v1/publicFood/getDeviceList?access_token=${app.globalData.access_token}`;
  //   const params = {
  //     "header": {
  //       "deviceCode": app.globalData.mac
  //     },
  //     "data": {
  //       "catalogId": 99
  //     }
  //   };
  //   call.postData(url, params, res => {
  //     console.log('自定义食材列表', res)
  //     this.setData({
  //       foodKindList: res.data
  //     })
  //   }, err => {
  //     wx.showToast({
  //       title: '获取自定义食材失败',
  //       icon: 'none',
  //       duration: 2000
  //     })
  //   })
  // },
  // 将食材加入待选列表
  onAdd(e) {
    let that = this;
    if (that.data.waitList.find(i => i.id === e.currentTarget.dataset.attrList.id)) { //如果点击已在待选列表中的食物
      const newList = this.data.waitList.filter(i => i.id !== e.currentTarget.dataset.attrList.id)
      this.setData({
        waitList: newList,
        activeFood: ''
      })
    } else {
      const wait = this.data.waitList;
      const newAttrList = e.currentTarget.dataset.attrList;
      newAttrList.dateOfProduct = (new Date().getTime());
      wait.push(newAttrList);
      this.setData({
        waitList: wait,
        activeFood: e.currentTarget.dataset.attrList.id
      });
    }
  },
  // 打开/编辑食材详情
  onOpenInfo(e) {
    const info = e.currentTarget.dataset.item;
    this.setData({
      info: info,
      dateOfProduct: info.dateOfProduct,
      shelfLife: info.shelfLife
    });
  },
  cancelInfo() {
    this.setData({
      info: ''
    });
  },
  bindDateChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },
  subEvent(e) {
    const detail = e.detail
    const shelfLife = detail.number * ((detail.unit === '天' && 1) || (detail.unit === '月' && 30) || (detail.unit === '年' && 365))
    this.setData({
      shelfLife: shelfLife
    });
    console.log('提交的数据', detail);
  },
  subEventDate(e) {
    const newDate = new Date(e.detail.year + '-' + e.detail.month + '-' + e.detail.day);
    const timeStamp = newDate.getTime();
    this.setData({
      dateOfProduct: timeStamp
    })
    console.log('计算后的时间戳', timeStamp);
  },
  subChange() {
    var that = this;
    const { waitList, info, dateOfProduct, shelfLife} = that.data;
    wx.showModal({
      title: '确认修改',
      content: '确认要提交本次修改么？',
      success(res) {
        if (res.confirm) {//用户点击确定
          const newWait = waitList.slice().filter(i => i.id !== info.id);
          const newInfo = info;
          newInfo.dateOfProduct = dateOfProduct; //修改生产日期
          newInfo.shelfLife = shelfLife;//修改保质期
          newWait.push(newInfo); //把修改后的食材信息放进待选列表
          wx.showLoading({ //增加加载图标
            title: '稍后...',
          })
          that.setData({
            info: '',
            waitList: newWait
          }, () => { //成功设置属性之后
            wx.hideLoading(); //去掉加载图标
            wx.showToast({
              title: '加载成功',
            })
            console.log('修改后的待选列表', that.data.waitList)
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
      fail() {}
    });
  },
  prevent() {
    console.log('组织事件冒泡')
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})